package org.creavi.engine.model;

import java.io.IOException;
import java.util.ArrayList;

import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
import com.jme.util.export.Savable;

public class MeshDefinition implements Savable {
	private long id;
	
	private String texture;
	
	private ArrayList<MeshPart> keyframes;
	
	private int uses;
	
	public MeshDefinition() {
		
	}

	public MeshDefinition(long id) {
		super();
		this.id = id;
		this.keyframes = new ArrayList<MeshPart>();
	}

	public ArrayList<MeshPart> getKeyframes() {
		return keyframes;
	}

	public int getUses() {
		return uses;
	}

	public void setUses(int uses) {
		this.uses = uses;
	}
	
	public synchronized void use() {
		uses++;
		
		for (MeshPart part : keyframes) {
			part.use();
		}
	}
	
	public synchronized void release() {
		uses--;
		
		for (MeshPart part : keyframes) {
			part.release();
		}
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getTexture() {
		return texture;
	}

	public void setTexture(String texture) {
		this.texture = texture;
	}

	public Class<?> getClassTag() {
		return getClass();
	}

	@SuppressWarnings("unchecked")
	public void read(JMEImporter im) throws IOException {
		InputCapsule ic = im.getCapsule(this);
		id = ic.readInt("id", 0);
		texture = ic.readString("texture", null);
		uses = ic.readInt("uses", 0);
		keyframes = ic.readSavableArrayList("keyframes", new ArrayList<MeshPart>());
	}

	public void write(JMEExporter ex) throws IOException {
		OutputCapsule oc = ex.getCapsule(this);
		oc.write(id, "id", 0);
		oc.write(texture, "texture", null);
		oc.write(0, "uses", 0);
		oc.writeSavableArrayList(keyframes, "keyframes", null);
	}
}
